package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.similarity.ScriptedSimilarity;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ValueCountAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        //创建查询请求对象 指定索引库
        SearchRequest request = new SearchRequest("hotel");
        //构建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder functionScoreQuery = getQueryBuilder(params);
        //指定查询条件
        sourceBuilder.query(functionScoreQuery);
        //构建分页查询
        sourceBuilder.from((params.getPage() - 1) * params.getSize());
        sourceBuilder.size(params.getSize());

        //添加距离由近到远排序
        if (!StringUtils.isEmpty(params.getLocation())) {
            /*GeoDistanceSortBuilder sort=new GeoDistanceSortBuilder("location",new GeoPoint(params.getLocation()));
            sort.order(SortOrder.ASC);
            sort.unit(DistanceUnit.KILOMETERS);
            sourceBuilder.sort(sort);*/
            System.out.println(params.getLocation());
            sourceBuilder.sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }
        //分值排序
        if ("default".equals(params.getSortBy())) {
            sourceBuilder.sort("_score", SortOrder.DESC);
        }
        if ("price".equals(params.getSortBy())) {
            sourceBuilder.sort("price", SortOrder.ASC);
        }
        if ("score".equals(params.getSortBy())) {
            sourceBuilder.sort("score", SortOrder.DESC);
        }
        //添加高亮
        if (!StringUtils.isEmpty(params.getKey())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<em>").postTags("</em>").
                    field("name");
            sourceBuilder.highlighter(highlightBuilder);
        }
        request.source(sourceBuilder);
        //发送查询请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取总数
            SearchHits hits = response.getHits();
            Long total = hits.getTotalHits().value;
            //获取酒店信息数据
            List<HotelDoc> list = new ArrayList<>();
            SearchHit[] searchHits = hits.getHits();
            if (searchHits.length > 0) {
                for (SearchHit searchHit : searchHits) {
                    System.out.println(searchHit);
                    String sourceAsString = searchHit.getSourceAsString();
                    HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
                    if (params.getLocation() != null) {
                        Object[] sortValues = searchHit.getSortValues();
                        hotelDoc.setDistance(sortValues[0]);
                    }
                    if (params.getKey() != null) {
                        HighlightField highlightField = searchHit.getHighlightFields().get("name");
                        if (highlightField != null) {
                            Text[] fragments = highlightField.getFragments();
                            String name = fragments[0].toString();
                            hotelDoc.setName(name);
                        }
                    }
                    list.add(hotelDoc);
                }
            }
            //封装page
            PageResult pageResult = new PageResult();
            pageResult.setHotels(list);
            pageResult.setTotal(total);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map<String, List<String>> filter(RequestParams params) {
        List<String> cityList = new ArrayList<>();
        List<String> brandList = new ArrayList<>();
        List<String> starNameList = new ArrayList<>();
        //创建查询请求对象，指定索引库
        SearchRequest request=new SearchRequest("hotel");
        //根据参数获取查询条件
        QueryBuilder queryBuilder = getQueryBuilder(params);
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        //指定查询条件
        sourceBuilder.query(queryBuilder);
        sourceBuilder.size(0);
        //聚合运算
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        brandAgg.field("brand");
        sourceBuilder.aggregation(brandAgg);
        TermsAggregationBuilder cityAgg = AggregationBuilders.terms("cityAgg");
        cityAgg.field("city");
        sourceBuilder.aggregation(cityAgg);
        TermsAggregationBuilder starNameAgg = AggregationBuilders.terms("starNameAgg");
        starNameAgg.field("starName");
        sourceBuilder.aggregation(starNameAgg);
        request.source(sourceBuilder);
        try {
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //添加结果
            Aggregations aggregations = response.getAggregations();

                Terms brandResult = aggregations.get("brandAgg");
                for (Terms.Bucket bucket : brandResult.getBuckets()) {
                    String keyAsString = bucket.getKeyAsString();
                    brandList.add(keyAsString);
                }


                Terms cityResult = aggregations.get("cityAgg");
                for (Terms.Bucket bucket : cityResult.getBuckets()) {
                    String keyAsString = bucket.getKeyAsString();
                    cityList.add(keyAsString);
                }


                Terms starResult = aggregations.get("starNameAgg");
                for (Terms.Bucket bucket : starResult.getBuckets()) {
                    String keyAsString = bucket.getKeyAsString();
                    starNameList.add(keyAsString);
                }


        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, List<String>> map = new HashMap<>();
        map.put("city",cityList);
        map.put("brand",brandList);
        map.put("starName",starNameList);

        return map;

    }

    /**
     * 根据参数构建查询条件
     * @param params
     * @return
     */
    public QueryBuilder getQueryBuilder(RequestParams params) {
        //多条件查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(params.getKey())) {
            //sourceBuilder.query(QueryBuilders.matchAllQuery());
            queryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            //sourceBuilder.query(QueryBuilders.matchQuery("name",params.getKey()));
            queryBuilder.must(QueryBuilders.matchQuery("name", params.getKey()));
        }
        //添加过滤条件
        if (!StringUtils.isEmpty(params.getCity())) {
            queryBuilder.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if (!StringUtils.isEmpty(params.getStarName())) {
            queryBuilder.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if (!StringUtils.isEmpty(params.getBrand())) {
            queryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (!StringUtils.isEmpty(params.getMinPrice())) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()));
        }
        if (!StringUtils.isEmpty(params.getMaxPrice())) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()));
        }
        //添加竞价权重
        return QueryBuilders.functionScoreQuery(queryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true), ScoreFunctionBuilders.weightFactorFunction(10))
        });
    }
}
